// 引入User 实体
import {User} from "../domain/User.ts";
// 引入uuid
import {v4} from "http://deno.land/std/uuid/mod.ts";

// 定义User集合
let Users : User[] = [
    {
        id : "1",
        name: "张三",
        address:"北京市丰台区朝阳路29号1号楼2903",
        age: 18
    },
    {
        id : "2",
        name: "李四",
        address:"陕西省西安市雁塔区长丰路29号 1单元 3002",
        age: 17
    }
]

//@desc         获取所有用户
//@router       GET /api/v1/users
const getUsers = ({response} : {response:any}) => {
    response.body = {
        success : true,
        data: Users
    }
}


//@desc         获取单个用户
//@router       GET /api/v1/users/:id
const getUser = ( {params,response} : {params:{id:string}, response:any}) => {

    const user : User | undefined = Users.find(u => u.id === params.id);
    if(user){
        response.status = 200;
        response.body = {
            success : true,
            data: user
        }
    }else{
        response.status = 200;
        response.body = {
            success : false,
            message: "没有找到该用户"
        }
    }
}


//@desc         添加用户
//@router       POST /api/v1/users/
const addUser = async ({request,response} : {request:any,response:any}) => {

     const body = await request.body(true);
     if(!request.hasBody){
        response.status = 400;
        response.body = {
            success : false,
            message: "没有数据"
        }
     }else{
         const addUser : User = await body.value;
         addUser.id = v4.generate();
         Users.push(addUser);
         response.status = 200;
         response.body ={
             success : true,
             data: addUser
         }
     }
}


//@desc         修改用户
//@router       PUT /api/v1/users/:id
const updateUser = async ({params, request, response} : 
    {params:{id:string},request:any,response:any}) => 
{
    const user : User | undefined = Users.find(u => u.id === params.id);
    if(user){
        
        const body = await request.body();
        const updateUser : {name? : String, address? : String, age? : number} = await body.value;

        console.log(updateUser);
        // 展开运算符
        Users = Users.map(u => u.id == params.id ? 
            {...u, ...updateUser}: u);

        response.status = 200;
        response.body = {
            success : true,
            data:Users
        }

    }else{
        response.status = 404;
        response.body = {
            success : false,
            message: "没有找到该用户"
        }
    }
}


//@desc         删除用户
//@router       DELTE /api/v1/users/:id
const delteUser = ({params,response} : {params : {id : string}, response:any}) => {
    Users = Users.filter(u => u.id !== params.id)
    response.status = 200;
    response.body = {
        success : true,
        data: Users
    }
}


export {getUsers, getUser, addUser, updateUser, delteUser};

